﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace nCoV2019_Predict
{
    public class DataHelper
    {
        string fileGlobal = Path.Combine(Application.StartupPath, "nCoV2019_Predict_data_Global.json");
        string dataString;
        string DataString
        {
            get
            {
                if (string.IsNullOrWhiteSpace(dataString))
                {
                    return File.ReadAllText(fileGlobal);
                }
                else
                {
                    return dataString;
                }
            }
        }
        public Task<bool> DownLoadGlobalHistoryNew()
        {
            return Task.Run(() =>
            {
                var succeed = false;
                try
                {
                    var dataStringNew = new WebClient { Encoding = Encoding.UTF8 }.DownloadString("https://coronavirus-tracker-api.herokuapp.com/all");
                    if (dataString != dataStringNew)
                    {
                        dataString = dataStringNew;
                        Write(fileGlobal, dataString);
                        succeed = true;
                    }
                }
                catch (Exception)
                {

                }
                return succeed;
            });
        }
        public DataRaw[] ParseGlobalHistory(string country = "All")
        {
            Dictionary<string, int> Get(dynamic dataType)
            {
                var dic = new Dictionary<string, int>();
                var od = new List<string>();
                foreach (var i in dataType)
                {
                    od.Add(i.country.Value);
                    if (country != "All" && i.country.Value != country)
                    {
                        continue;
                    }
                    var v = i.history;
                    foreach (var item in v)
                    {
                        var day = item.Name;
                        var val = int.Parse(item.Value.Value.ToString());
                        if (dic.ContainsKey(day))
                        {
                            dic[day] += val;
                        }
                        else
                        {
                            dic.Add(day, val);
                        }
                    }
                }
                var nd = od.Distinct().OrderBy(i => i).ToArray();
                var d = new DataTable();
                d.Columns.Add();
                foreach (var item in nd)
                {
                    d.Rows.Add(item);
                }
                return dic;
            }

            var json = JsonConvert.DeserializeObject<dynamic>(DataString);
            var confirmed = Get(json.confirmed.locations);
            var recovered = Get(json.recovered.locations);
            var deaths = Get(json.deaths.locations);

            var da = new List<DataRaw>();
            foreach (var item in confirmed)
            {
                try
                {
                    var day = item.Key.Split('/');
                    day[2] = "20" + day[2];
                    da.Add(new DataRaw()
                    {
                        date = string.Join("/", day),
                        confirm = item.Value,
                        heal = recovered[item.Key],
                        dead = deaths[item.Key]
                    });
                }
                catch (Exception)
                {
                }
            }

            return da.ToArray();
        }
        public dynamic ParseGlobalNow()
        {
            var json = JsonConvert.DeserializeObject<dynamic>(DataString);
            var od = new { updateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), confirm = json.latest.confirmed.ToString(), heal = json.latest.recovered.ToString(), dead = json.latest.deaths.ToString() };
            return $"更新时间UpdateTime：{od.updateTime}，确诊Confirm：{od.confirm}，治愈Heal：{od.heal}，死亡Dead：{od.dead}";
        }

        #region 原中国数据采用腾讯数据源
        string fileChina = Path.Combine(Application.StartupPath, "nCoV2019_Predict_data_China.json");
        public DataRaw[] GetChinaHistory()
        {
            var dataString = new WebClient { Encoding = Encoding.UTF8 }.DownloadString("https://view.inews.qq.com/g2/getOnsInfo?name=wuwei_ww_cn_day_counts");
            Write(fileChina, dataString);
            var dataJson = JsonConvert.DeserializeObject<RootObject>(dataString).data;
            return JsonConvert.DeserializeObject<DataRaw[]>(dataJson);
        }
        public dynamic GetChinaNow()
        {
            var dataString = new WebClient { Encoding = Encoding.UTF8 }.DownloadString("https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5");
            var DataJson = JsonConvert.DeserializeObject<RootObject>(dataString).data;
            dynamic json = JValue.Parse(DataJson);
            var od = new { updateTime = json.lastUpdateTime.ToString(), confirm = json.chinaTotal.confirm.ToString(), heal = json.chinaTotal.heal.ToString(), dead = json.chinaTotal.dead.ToString() };
            return $"更新时间UpdateTime：{od.updateTime}，确诊Confirm：{od.confirm}，治愈Heal：{od.heal}，死亡Dead：{od.dead}";
        }
        #endregion

        private void Write(string file, string dataString)
        {
            try
            {
                if (File.Exists(file) && !string.IsNullOrWhiteSpace(dataString))
                    File.Delete(file);
                File.WriteAllText(file, dataString);
            }
            catch (Exception)
            {
            }
        }
    }
}
